# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(optparse)
library(magrittr)
library(tidyverse)
library(ggrepel)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--config", default = "config.csv", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote"))

configData <- read.csv(opt$config, header = F, stringsAsFactors = F) %>%
  set_colnames(c("arg", "value")) %>%
  column_to_rownames("arg")

configData

pValue <- configData["diffMethod.pValue", "value"] %>%
  as.numeric()
fdr <- configData["diffMethod.fdr", "value"] %>%
  as.numeric()
log2FC <- configData["diffMethod.log2FC", "value"] %>%
  as.numeric()

parent <- "./"
createWhenNoExist(parent)
fileName <- paste0(parent, "AllMet_Test.csv")
outFileName <- paste0(parent, "/Volcano_Plot_with_Label.pdf")
data <- read_csv(fileName) %>%
  filter(is.finite(FC))

head(data)

log2FCVec <- c(log2FC, -log2FC)

logP5 <- -log(pValue)
logFdr5 <- -log(fdr)

pFilterData <- data %>%
  filter(P < pValue)

fdrFilterData <- data %>%
  filter(FDR <= fdr)

useP <- if (nrow(pFilterData) < nrow(fdrFilterData)) {
  TRUE
}else FALSE

plotDataWithLog <- if (useP) {
  data %>%
    mutate(logP = -log(P))
}else {
  data %>%
    mutate(logP = -log(FDR))
}

yLabel <- if (useP) {
  "-ln(P)"
}else "-ln(FDR)"

hLineY <- if (useP) {
  logP5
}else logFdr5

hLineLabel <- if (useP) {
  str_c("P=", pValue)
}else  str_c("FDR=", fdr)

plotData <- plotDataWithLog %>%
  rowwise() %>%
  do({
       result <- as.data.frame(.)
       logP <- result["logP"]
       tmpLog2FC <- result[1, "log2FC"]
       q <- result[1, "FDR"]
       p <- result[1, "P"]
       col <- if (p < pValue &
         abs(tmpLog2FC) >= log2FC &
         q <= fdr &
         tmpLog2FC >= 0) {
         "UP"
       }else if (p < pValue &&
         abs(tmpLog2FC) >= log2FC &&
         q <= fdr &
         tmpLog2FC < 0) {
         "DOWN"
       }  else "NONE"
       result$col <- col
       result
     }) %>%
  mutate(col = factor(col, levels = c("UP", "DOWN", "NONE"))) %>%
  as.data.frame()

finitePlotData <- plotData %>%
  filter(is.finite(log2FC))

minX <- finitePlotData %>%
  .$log2FC %>%
  min()
maxX <- finitePlotData %>%
  .$log2FC %>%
  max()
absMaxX <- max(abs(maxX), abs(minX))
annoX <- -absMaxX
breaks <- seq(-ceiling(absMaxX), ceiling(absMaxX), 2)

upNum <- plotData %>%
  filter(col == "UP") %>%
  nrow()

downNum <- plotData %>%
  filter(col == "DOWN") %>%
  nrow()

noneNum <- plotData %>%
  filter(col == "NONE") %>%
  nrow()

pointCols <- tibble(sig = c("UP", "DOWN", "NONE"), col = c("red", "blue", "#BEBEBE")) %>%
  deframe()

pointLabels <- tibble(sig = c("UP", "DOWN", "NONE"),
                      label = c(str_c("UP:", upNum), str_c("DOWN:", downNum), str_c("NONE:", noneNum))) %>%
  deframe()

upDownTb <- plotData %>%
  filter(col %in% c("UP", "DOWN"))

print(plotData)

p <- ggplot(plotData, mapping = aes(x = log2FC, y = logP, colour = col)) +
  theme_bw(base_size = 8.8, base_family = "Times") +
  theme(axis.text.x = element_text(size = 9, vjust = 0.5),
        axis.text.y = element_text(size = 8.8), legend.position = 'right',
        axis.title.y = element_text(size = 11), legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'),
        legend.text = element_text(size = 9), axis.title.x = element_text(size = 11), panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), plot.title = element_text(hjust = 0.5, size = 13)
  ) +
  ylab(yLabel) +
  ggtitle("") +
  geom_hline(aes(yintercept = hLineY), colour = "#A9A9A9", linetype = 2, size = 0.375) +
  annotate("text", x = annoX, y = hLineY + 0.1, label = hLineLabel, color = "black", vjust = 0, hjust = 0,
           size = 3, family = "Times") +
  geom_vline(aes(xintercept = log2FCVec[1]), colour = "#A9A9A9", linetype = 2, size = 0.3) +
  geom_vline(aes(xintercept = log2FCVec[2]), colour = "#A9A9A9", linetype = 2, size = 0.3) +
  scale_x_continuous("log2FC", breaks = breaks, limits = c(-ceiling(absMaxX), ceiling(absMaxX))) +
  scale_colour_manual("", values = pointCols, labels = pointLabels) +
  #point
  geom_point(aes(), size = 2, stroke = 0) +
  geom_text_repel(segment.size = 0.2, data = upDownTb, aes(x = log2FC, y = logP, label = Metabolite), size = 2, family = "Times",
                  color = "black")

ggsave(limitsize = FALSE, outFileName, p, width = 7, height = 5)





